from flask import request, jsonify

from app import db
from app.models import Model, Apply

from flask import Blueprint

result_bp = Blueprint('result1', __name__)


# 上传模型
@result_bp.route('/upload_model', methods=['POST'])
def upload_model():
    data = request.json
    model_name = data.get('model_name')
    model_address = data.get('model_address')
    model_describe = data.get('model_describe')

    model = Model(model_name=model_name, model_address=model_address, model_describe=model_describe)
    db.session.add(model)
    db.session.commit()

    return jsonify({'message': 'Model uploaded successfully'}), 201


# 获取所有可用模型列表
@result_bp.route('/available_models')
def available_models():
    models = Model.query.filter_by(model_state=1).all()
    result = []
    for model in models:
        result.append({
            'model_id': model.model_id,
            'model_name': model.model_name,
            'model_address': model.model_address,
            'model_describe': model.model_describe
        })
    return jsonify(result)


# 申请使用他人模型
@result_bp.route('/apply_for_model', methods=['POST'])
def apply_for_model():
    data = request.json
    applicant_id = data.get('applicant_id')
    model_id = data.get('model_id')
    apply_describe = data.get('apply_describe')

    apply = Apply(applicant_id=applicant_id, model_id=model_id, apply_describe=apply_describe)
    db.session.add(apply)
    db.session.commit()

    return jsonify({'message': 'Application submitted successfully'}), 201


# 对申请进行拒绝
@result_bp.route('/reject_application/<int:apply_id>', methods=['PUT'])
def reject_application(apply_id):
    apply = Apply.query.get(apply_id)
    if apply:
        apply.apply_state = 2  # 设置申请状态为拒绝
        db.session.commit()
        return jsonify({'message': 'Application rejected successfully'}), 200
    else:
        return jsonify({'error': 'Application not found'}), 404
